/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.service.impl;

import com.workcell.workdata.im.component.event.BucketCreatedEvent;
import com.workcell.workdata.im.component.event.ImageUploadEvent;
import com.workcell.workdata.im.configuration.properties.FileLocalProperties;
import com.workcell.workdata.im.constant.Common;
import com.workcell.workdata.im.constant.FileBucket;
import com.workcell.workdata.im.model.vo.UploadSignVO;
import com.workcell.workdata.im.service.FileStoreService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.FileSystems;

/**
 * 文件存储在本地文件夹的策略下 文件管理实现
 */
public class LocalFileServiceImpl implements FileStoreService, ApplicationListener<ApplicationStartedEvent> {
	private static final Logger LOGGER = LoggerFactory.getLogger(LocalFileServiceImpl.class);
	private File jarFilePath;
	private static final String REF_COUNT_FILE = "%s.ref";

	private final FileLocalProperties properties;

	private final String fileSeparator = FileSystems.getDefault().getSeparator();

	@javax.annotation.Resource
	private ApplicationContext applicationContext;

	public LocalFileServiceImpl(FileLocalProperties properties){
		this.properties = properties;
	}

	@Override
	public void delete(String bucket, String key) {
		if (StringUtils.isBlank(bucket)
				|| StringUtils.isBlank(key)) {
			return;
		}

		File targetFile = new File(getBaseBucketPath(), bucket + fileSeparator + key);

		if (getReferenceCount(targetFile) == 0){
			FileUtils.deleteQuietly(targetFile);
			return;
		}

		addReferenceCount(targetFile,-1);
	}

	@Override
	public void addReferenceCount(String bucket, String key){

		File targetFile = new File(getBaseBucketPath() , bucket  + fileSeparator + key);

		addReferenceCount(targetFile,1);
	}

	/**
	 * 适配三方存储获取签名 客户端直传
	 * @param bucket
	 * @param name
	 * @return
	 */
	@Override
	public UploadSignVO getUploadSign(String bucket, String name) {
		UploadSignVO signVO = new UploadSignVO();
		signVO.setHost(String.format(properties.getHost(),bucket,name));
		return signVO;
	}


	@Override
	public void upload(MultipartFile file, String bucket, String key) {

		File desFile = new File(getBaseBucketPath(),bucket  + fileSeparator + key);
		FileUtils.deleteQuietly(desFile);
		try {
			file.transferTo(desFile);
			applicationContext.publishEvent(new ImageUploadEvent(bucket,key));
		} catch (Exception e) {
			LOGGER.error("upload local file error",e);
		}
	}

	@Override
	public Resource get(String bucket, String key) {

		File destFile = new File(getBucket(bucket), key);

		if (destFile.exists() && destFile.length() == 0L){
			FileUtils.deleteQuietly(destFile);
			return null;
		}

		if (destFile.exists() && destFile.length() > 0L){
			return new FileSystemResource(destFile);
		}

		String defaultFileName =  FileBucket.getDefaultFilename(bucket);
		if (defaultFileName == null){
			return null;
		}

		File defaultFile = new File(getBucket(bucket), defaultFileName);

		return defaultFile.exists() ? new FileSystemResource(defaultFile) : null;
	}

	public String getBaseBucketPath() {
		return new File(jarFilePath, Common.LOCAL_BUCKET).getAbsolutePath();
	}


	private int getReferenceCount(File file){

		File countFile = new File(file.getParent(),String.format(REF_COUNT_FILE,file.getName()));

		try {
			return !countFile.exists() ? 0 :  Integer.parseInt(FileUtils.readFileToString(countFile));
		}catch (Exception ignore){
			return 0;
		}
	}


	public void addReferenceCount(File file,int add){

		File countFile = new File(file.getParent(),String.format(REF_COUNT_FILE,file.getName()));
		if (!countFile.exists() && add < 0){
			return;
		}

		try {
			if (!countFile.exists()){
				countFile.createNewFile();
			}

			String text = FileUtils.readFileToString(countFile);

			int count =  text == null ? 0 : Integer.parseInt(text);

			FileUtils.write(countFile,String.valueOf(count + add));

		}catch (Exception ignore){}

	}

	private File getBucket(String bucket) {
		return  new File(getBaseBucketPath(),bucket);
	}

	@Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
		ApplicationHome home = new ApplicationHome(getClass());
		if (home.getSource() != null) {
			jarFilePath = home.getSource().getParentFile();
		}else {
			jarFilePath = home.getDir();
		}

		File bucketDir = new File(getBaseBucketPath());

		try {

			FileUtils.forceMkdir(bucketDir);

			for (String bucket : properties.getBuckets()) {
				FileUtils.forceMkdir(new File(bucketDir, bucket));
			}

			applicationContext.publishEvent(new BucketCreatedEvent(bucketDir));

		}catch (Exception ignore){}

	}
}
